package Source;

import Questions.AnswerQuestion;
import Questions.Question;
import Questions.TestQuestion;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Source.UserController: Инесса
 * Date: 20.10.13
 * Time: 2:10
 * To change this template use File | Settings | File Templates.
 */
public class QuestionsFromFile implements QuestionsSource {
    /**
     * Создает массив вопросов прочитанных из файла.
     * @return  массив вопросов
     * @throws IOException
     */
    @Override
    public Question[] getQuestions() throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader("QuestionsAnswers.csv"));
        String nextLine;
        Question question;
        List<Question> questions = new ArrayList<>();
        final int QUESTION_WITHOUT_CHOICE_OF_ANSWERS = 2;
        while ((nextLine = reader.readLine()) != null) {
            String[] questionsAndRightAnswerFromFile = nextLine.split(",");
            if (questionsAndRightAnswerFromFile.length == QUESTION_WITHOUT_CHOICE_OF_ANSWERS) {
                question = new AnswerQuestion(questionsAndRightAnswerFromFile[0],questionsAndRightAnswerFromFile[1].trim());
            } else {
                question = new TestQuestion(questionsAndRightAnswerFromFile[0],questionsAndRightAnswerFromFile[1].trim(),
                      Arrays.copyOfRange(questionsAndRightAnswerFromFile, 2, questionsAndRightAnswerFromFile.length));
            }
            questions.add(question);
        }
        return questions.toArray(new Question[questions.size()]);
    }
}
